<%@ page import="com.kma.ncpractice2013.dao.UserDAO" %>
<%@ page import="com.kma.ncpractice2013.dao.UserGroupDAO" %>
<%@ page import="com.kma.ncpractice2013.model.User" %>
<%@ page import="com.kma.ncpractice2013.model.UserGroup" %>
<%@ page import="com.kma.ncpractice2013.model.Commission" %>
<%--
  User: Viktor
  Date: 10/24/13
--%>

<%  String sessionAuth = (String)session.getAttribute("auth");
    double dsc = 0;
    double comm = 0;
    if(sessionAuth !=null && sessionAuth.equals("true"))
    {



            //int userAccessLevel = Integer.parseInt((String)session.getAttribute("access_level"));
            UserDAO userDAO = new UserDAO();
            User user = userDAO.getByLogin((String)session.getAttribute("username"));
            UserGroupDAO userGroupDAO = new UserGroupDAO();
            UserGroup userGroup = userGroupDAO.getById(user.getGroupId().getValue());
            dsc = userGroup.getDiscount();
            //comm = userGroup.getCommission();
            comm = Commission.getValue();


    }
%>

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <style type="text/css">
        div.color
        {
            border-bottom: 2px dotted #ff9900;
        }
        input.searchControls
        {
            left: 0;

        }
        button.searchControls
        {
            left: 0;
        }
    </style>

    <script type = "text/javascript" src="http_code.jquery.com_jquery-1.5.1.js"></script>

    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">

    <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
    <script type="text/javascript">
        var res;
        var promocodeDiscount = 0;
        var discount = "<%=dsc%>";
        var commission = "<%=comm%>";

        function roundToTwo(num) {
            return +(Math.round(num + "e+2")  + "e-2");
        }
        function dateParse(date)
        {
            var dateparts = date.split("/");
            var datestring = dateparts[2] + "-" + dateparts[0] + "-" +  dateparts[1];
            return datestring;

        }

        function ShowResults()
        {
            $('.results').empty();
            if(res.hasOwnProperty('Result'))
            {
            $.each(res.Result, function (index, element)
            {
                var discountedPrice = roundToTwo(element.TotalPrice * (1 + (commission / 100) * (1 - (discount+promocodeDiscount) / 100)));
                var neighbourhood = $.grep(res.MetaData.HotelMetaData.Neighborhoods, function (e)
                {
                    return e.Id == element.NeighborhoodId;
                })[0];
                $('.results').append($('<div id = index class = "color" >' +
                        neighbourhood.Name + '<br/>' +
                        "Base price: " + element.CurrencyCode + " " + element.TotalPrice + '<br/>' +
                        "With commission and discount: " + element.CurrencyCode + " " + discountedPrice + '<br/>' +
                        "Check-in Date " + element.CheckInDate + '<br/>' +
                        "Check-out Date " + element.CheckOutDate + '<br/>' +
                        "Nights: " + element.Nights + '<br/>' +
                        "Rooms: " + element.Rooms + '<br/>' +
                        "Star rating: " + element.StarRating + '<br/>' +
                        "<form method='post' action='Order'>" +
                        "<input type='hidden' name='hotelDesc' value=" + encodeURIComponent(JSON.stringify(element)) + ">" +
                        "<input type='hidden' name='neighbourhood' value=" + encodeURIComponent(JSON.stringify(neighbourhood)) + ">" +
                        "<input type='hidden' name='username' value=" + $('#username').val() + ">" +
                        "<input type='hidden' name='price' value=" + discountedPrice + ">" +
                        "<input type='hidden' name='checkindate' value=" + dateParse(element.CheckInDate) + ">" +
                        "<input type='hidden' name='checkoutdate' value=" + dateParse(element.CheckOutDate) + ">" +
                        "<input type='hidden' name='adults' value=" + $('#adults').val() + ">" +
                        "<input type='hidden' name='children' value=" + $('#children').val() + ">" +
                        "<input type='submit' value='Order'>" +
                        "</form>" +
                        "<input type='button' value='Show on map'>" +
                        "<input type='button' value='Show more' onclick='Expand(index)'>" +
                        "</form>"

                        + '</div>'));
            });
            }else
            {
                $('.results').append($('<div>', {
                    text: "No results"
                }));
            }
        }
        function MakeQuery()
        {

            $.ajax(
                    {
                        type: "POST",
                        contentType: "application/json; charset=utf-8",
                        url: createHotwireURL(),
                        dataType: 'jsonp',
                        async:true,
                        success: function (data)
                        {
                            res = data;
                            ShowResults();
                        },
                        error: function ()
                        {
                            $('.results').append($('<div>', {
                                text: "Error"
                            }));
                        }


                    });

        }
        function createHotwireURL()
        {
            var str1 = 'https://api.hotwire.com/v1/search/hotel?apikey=65w49vx9saqwuf2j66774ab3&format=jsonp';
            var deststr = "&dest="+document.getElementById("dest").value;
            var checkindate = "&startdate="+parseDate(document.getElementById("checkin").value.toString());
            var checkoutdate = "&enddate="+parseDate(document.getElementById("checkout").value.toString());
            var rooms = "&rooms="+document.getElementById("rooms").value.toString();
            var adults = "&adults="+document.getElementById("adults").value.toString();
            var children = "&children="+document.getElementById("children").value.toString();
            return str1+deststr+rooms+adults+children+checkindate+checkoutdate;

        }

        function CheckPromocode()
        {
            //TODO: real check
            if($('#promocode').val() == "qqq")
            {
                $('#promocode').css('background-color', 'greenyellow');
                promocodeDiscount = 7;
                ShowResults();
            }
            else
            {
                $('#promocode').css('background-color', 'indianred');
            }
        }

        function Expand(divId)
        {

        }

        function ErrorFunction()
        {

            document.getElementById('jsResult').innerHtml="something wrong happened";
        }
        function parseDate(date)
        {
            var arr = date.split('-');
            return arr[1]+'/'+arr[2]+'/'+arr[0];

        }
        var map;
        function initialize() {
            var mapOptions = {
                zoom: 8,
                center: new google.maps.LatLng(50.5, 30.6),
                mapTypeId: google.maps.MapTypeId.HYBRID
            };
            map = new google.maps.Map(document.getElementById('map-canvas'),
                    mapOptions);
            var marker = new google.maps.Marker({
                position: new google.maps.LatLng(50.5, 30.6),
                map: map,
                title: 'Hello World!'
            });
        }

        google.maps.event.addDomListener(window, 'load', initialize);
    </script>
</head>

<body>
<div style="left: 30; float: left; width: 50%; height: 100%;" class="results"></div>
<div style="position: fixed; float: right; left: 20; width: 50;">
<div style=" position: fixed; right: 10px; top: 20px; width: 20%; height: 50%;">
<input type="text" id="dest" placeholder="Destination" class="searchControls" value="Detroit"><br/>
<input type="date" id="checkin" class="searchControls"><br/>
<input type="date" id="checkout" class="searchControls"><br/>
<input type="text" id="rooms" placeholder="Rooms count" value="1" class="searchControls"><br/>
<input type="text" id="adults" placeholder="Adults count" value="1" class="searchControls"><br/>
<input type="text" id="children" placeholder="Children count" value="0" class="searchControls"><br/><br/>
    <%  //String sessionAuth = (String)session.getAttribute("auth");
        if(sessionAuth !=null && sessionAuth.equals("true"))
        {

            out.println("<input type=\"text\" class=\"searchControls\" id=\"username\" placeholder=\"username\" readonly=\"true\" value=\""+(String)session.getAttribute("username")+"\"><br/><br/>");
        }
        else
            out.println("<input type=\"text\" class=\"searchControls\" id=\"username\" placeholder=\"username\" readonly=\"true\"><br/><br/>");




    %>

<input type="text" id="promocode" placeholder="promocode" class="searchControls" >
<button type="button" onclick="CheckPromocode()" class="searchControls">Check code</button><br/>
<button type="button" onclick="MakeQuery()" class="searchControls">Show results</button>
</div>
<div id="map-canvas" style ="height : 50%; width : 50%;   position: fixed; bottom: 20px; right: 10px;"></div>
</div>


</body>
</html>